import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { changeProtocol } from '../utils/ruoyi';

function getImageExtension(filename) {
  return filename.split('.').pop().toLowerCase();
}

export async function obsUpload(file, callback) {
  try {
    let fileExtension = getImageExtension(file.file.name);
    let contentType = 'multipart/form-data';
    if (fileExtension == 'png') {
      contentType = 'image/png';
    } else if (fileExtension == 'gif') {
      contentType = 'image/gif';
    } else if (fileExtension == 'jpeg') {
      contentType = 'image/jpeg';
    } else if (fileExtension == 'jpg') {
      contentType = 'image/jpeg';
    }else if (fileExtension == 'webp') {
      contentType = 'image/webp';
    }

    const response = await request({
      url: `/common/getSignUrl`,
      method: 'post',
      data: { fileName: file.file.name, contentType: contentType },
    });

    if (response.code !== 200) {
      ElMessage.error(response.msg);
      return;
    }
    console.log(file.file.name);
    const singedUrl = changeProtocol(response.data.signedUrl || '');
    const responseStr = await fetch(singedUrl, {
      method: 'PUT',
      headers: { 'Content-Type': contentType },
      body: file.file, // 直接上传整个文件
    });

    if (!responseStr.ok) {
      throw new Error(`Upload failed, status: ${response.status}`);
    }

    callback(response.data);
    file.onSuccess && file.onSuccess(response, file.file);
  } catch (error) {
    ElMessage.error(error.message);
    file.onError && file.onError(error);
  }
}

/**
 * @param file 不适配el-upload
 * @returns {Promise<unknown>}
 */
export async function obsUploadPromise(file) {
  return new Promise(async (resolve, reject) => {
    try {
      // 获取签名 URL
      const response = await request({
        url: `/hospital-training/common/huawei/obs/getSignedUrl?fileName=${file.name}`,
        method: 'get',
      });

      if (response.code !== 200) {
        ElMessage.error(response.msg);
        reject(new Error(response.msg)); // 调用 reject
        return;
      }
      // 上传文件到签名 URL
      await request({
        url: response.data.signedUrl,
        method: 'PUT',
        headers: {
          'Content-Type': 'multipart/form-data',
          'Access-Control-Allow-Origin': '*',
        },
        data: file,
      });

      resolve(response.data);
    } catch (error) {
      // 错误处理
      ElMessage.error(error.message);
      reject(error);
    }
  });
}

export function getFileNameByUrl(url) {
  let format = url.substr(url.lastIndexOf('/') + 1);
  return format;
}
